/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.service.system.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cms.dao.system.AdminDao;
import org.grayrabbit.cms.dao.system.RoleDao;
import org.grayrabbit.cms.dao.system.RoleOperRelaDao;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.OperLog;
import org.grayrabbit.cms.entity.Role;
import org.grayrabbit.cms.entity.RoleOperRela;
import org.grayrabbit.cms.service.system.RoleService;
import org.grayrabbit.cms.vo.system.AdminBean;
import org.grayrabbit.cms.vo.system.RoleBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.grayrabbit.dao.util.Page;
import org.grayrabbit.service.impl.GenericServiceImpl;
/**
 * <b>OperLog</b>的service实现类，事务加此处：





 * @version 1.0,创建时间: 2011-05-16 15:55:03  
 */
@Service
@Transactional
public class RoleServiceImpl extends GenericServiceImpl implements RoleService {
	
	private static final Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);
	/**
	 * 注入dao层：
	 */
	@Autowired
	@Qualifier("roleDaoImpl")
	private RoleDao roleDao;
	
	@Autowired
	@Qualifier("adminDaoImpl")
	private AdminDao adminDao;
	
	
	@Autowired
	@Qualifier("roleOperRelaDaoImpl")
	private RoleOperRelaDao roleOperRelaDao;
	
	/**
	 * 此方法执行时为只读事务：
	 * @see RoleService#getOperLog(String)
	 */
	@Transactional(readOnly=true)
	public Role getRole(final String roleId){
		fillContext();
		Role role = RoleContext.getRoleById(roleId);
		return role;
	}
	
	/**
	 * @see RoleService#delete(String)
	 */
	@Transactional
	public boolean delete(final Role role) {
		boolean doDelete=false;
		int countUse=0;
		try{
			AdminBean ab=new AdminBean();
			ab.setRole(role);
			countUse+=adminDao.count(ab);
			
			List<RoleOperRela> rorList=null;
			if(0==countUse){
				if(StringUtils.isNotBlank(role.getRoleId())){
				 rorList= roleOperRelaDao.findAllAuthCodeByRoleId(role.getRoleId());
				}
				for(RoleOperRela r:rorList){
					roleOperRelaDao.makeTransient(r);
				}
				roleDao.makeTransient(role);
				doDelete=true;
			}else{
				doDelete=false;
			}
			
		}catch(Exception e){
			doDelete=false;
			log.debug("删除异常！");
		}
		RoleContext.UPDATE_FLAG=true;
		return doDelete;
	}
	
	/**
	 * 根据主键id列删除，批量删除OperLog
	 * @see RoleService#delete(String[])
	 */
	public boolean delete(final String[] key) {
		boolean doDelete=false;
		int countUse=0;
		Role role=null;
		AdminBean ab=null;
		List<RoleOperRela> rorList=null;
		for(String id : key){
			 ab=new AdminBean();
			 role=new Role(id);
			ab.setRole(role);
			countUse+=adminDao.count(ab);
		}
		if(0==countUse){
			int i =0;
			for(String id : key){
				if(StringUtils.isNotBlank(id)){
					 rorList= roleOperRelaDao.findAllAuthCodeByRoleId(id);
					}
					for(RoleOperRela r:rorList){
						roleOperRelaDao.makeTransient(r);
					}
				Role r = roleDao.findById(id);
				roleDao.makeTransient(r);
				for(Admin admin : role.getAdmins()){
					AdminContext.remove(admin.getLoginName());//清除用户缓存
				}
				i++;
				if(i==MAX_CLEAR)
					roleDao.clear();
				doDelete=true;
			}
		}else{
			doDelete=false;
		}
		RoleContext.UPDATE_FLAG=true;
		return doDelete;
	}
	/**
	 * @see RoleService#save(OperLog)
	 */
	@Transactional
	public void save(final Role role) {
		Role r = roleDao.makePersistent(role);
		for(Admin admin : r.getAdmins()){
			AdminContext.remove(admin.getLoginName());//清除用户缓存
		}
		RoleContext.UPDATE_FLAG=true;
	}
	
	/**
	 * 此方法执行时为只读事务：
	 * @see RoleService#getPage(RoleBean)
	 */
	@Transactional(readOnly=true)
	public Page<Role> getPage(final RoleBean roleBean){
		Page<Role> page =  new Page<Role>();
		page.setTotal(roleDao.count(roleBean));
		page.setResult(roleDao.findByQc(roleDao.assembly(roleBean)));
		return page;
	}

	/**
	 * 此方法执行时为只读事务：
	 * @see RoleService#list(Page, RoleBean)
	 */
	public void list(Page<Role> page, RoleBean roleBean) {
		if(page==null)
			return;
		if(page.isAutoCount()){
			page.setTotal(roleDao.count(roleBean));
		}
		List<Role> roles=roleDao.findByPage(page,roleBean);
		if(roles!=null){
			for(Role r:roles){
				roleDao.initialize(r.getAdmins());
			}
		}
		page.setResult(roles);
	}
	
	/**
	 * 获得相应激活状态的全部角色
	 */
	public List<Role> showAllRoles(Boolean active) {
		fillContext();
		List<Role> roles=RoleContext.getAllRoles(active);
		return roles;
	}

	public boolean roleActiveStatus(String[] key,boolean active){
		Role role=null;
		try {
			if(key!=null&&key.length>0){
				for(String str:key){
					role=roleDao.findById(str);
					role.setActiveStatus(active);
					roleDao.makePersistent(role);
					for(Admin admin : role.getAdmins()){
						AdminContext.remove(admin.getLoginName());//清除用户缓存
					}
				}
			}
		} catch (Exception e) {
			log.error("更新激活状态错误", e);
			return false;
		}
		RoleContext.UPDATE_FLAG=true;
		return true;
	}
	
	public boolean roleActiveStatus(String key,boolean active){
		String[] str=new String[1];
		str[0]=key;
		RoleContext.UPDATE_FLAG=true;
		return roleActiveStatus(str,active);
	}
	
	/**
	 * 启用/禁用
	 */
	public void disableOrEnable(String roleId) {
			Role r = roleDao.findById(roleId);
			if ((r != null) && (r.getActiveStatus() != null)
					&& (!r.getActiveStatus())) {
				r.setActiveStatus(true);
			} else {
				r.setActiveStatus(false);
			}
			roleDao.makePersistent(r);
			for(Admin admin : r.getAdmins()){
				AdminContext.remove(admin.getLoginName());//清除用户缓存
			}
			RoleContext.UPDATE_FLAG=true;
	}
	
	/**
	 * 检查角色名称唯一性
	 * @param role
	 * @return
	 */
	public boolean checkNameUnique(String roleName,String roleId){
		return roleDao.checkNameUnique(roleName,roleId);
	}
	
	/**
	 * 内存化数据字典
	 */
	private void fillContext(){
		if(RoleContext.UPDATE_FLAG){
			synchronized(RoleContext.lock){
				RoleContext.UPDATE_FLAG=false;
				RoleContext.remove();
				List<Role> roles=roleDao.findAll();
				for(Role role:roles){
					RoleContext.put(role);
				}
			}
		}
	}
}